package com.bulletelc.apollopre.module.richscan;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.constants.RegexConstants;
import com.bulletelc.apollopre.framework.BaseActivity;
import com.bulletelc.apollopre.interfaces.listener.PermissionListener;
import com.bulletelc.apollopre.module.display.product.details.ProductDetailsActivity;
import com.bulletelc.apollopre.utils.ImageUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.RegExUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CaptureFragment;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * author: lhl
 * time  : 2017/10/19
 * desc  : 自定义扫一扫界面
 */

public class RichScanActivity extends BaseActivity implements View.OnClickListener, PermissionListener {

    private CaptureFragment captureFragment;
    private Toolbar toolbar;

    private boolean rock = false; //是否重建fragment
    private static boolean open = false; // 手电筒是否打开

    @Override
    public int getLayoutRes() {
        return R.layout.rich_scan_activity;
    }

    @Override
    public void assignViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        initToolBar(toolbar, "");
        toolbar.inflateMenu(R.menu.menu_rich_scan);
    }

    @Override
    public void setListener() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RichScanActivity.this.finish();
            }
        });

        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menuImage:
                        //调用API打开图库
                        //Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                        //intent.addCategory(Intent.CATEGORY_OPENABLE);
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_PICK);
                        intent.setType("image/*");
                        startActivityForResult(intent, GlobalConfig.REQUEST_SYSTEM_IMAGE);
                        break;

                    case R.id.menuFlashlight:
                        if (!open) {
                            CodeUtils.isLightEnable(true);
                            item.setIcon(R.drawable.ic_flashlight_on);
                            open = true;
                        } else {
                            CodeUtils.isLightEnable(false);
                            item.setIcon(R.drawable.ic_flashlight_off);
                            open = false;
                        }
                        break;
                }
                return true;
            }
        });

    }


    @Override
    public void initData(Bundle savedInstanceState) {
        requestRuntimePermission(new String[]{Manifest.permission.CAMERA}, this);
    }

    @Override
    protected void setFullScreen() {
        //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_rich_scan, menu);
        return true;
    }

    /**
     * 二维码解析回调函数
     */
    CodeUtils.AnalyzeCallback analyzeCallback = new CodeUtils.AnalyzeCallback() {
        @Override
        public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
            //ToastUtil.showLongToast(RichScanActivity.this, "扫描结果:" + result);
            boolean containsId = result.contains("id=");
            boolean containSku = result.contains("sku/");
            boolean containSku2 = result.contains("sku=");
            //判断参数类型
            if (containsId) {
//                String id = result.substring(result.indexOf("id=") + 3);
                String id = MyUtil.getUrlValueByName(result, "id");
                boolean isInteger = RegExUtil.isMatch(RegexConstants.REGEX_POSITIVE_INTEGER, id);
                if (isInteger) {
                    Intent intent = new Intent(RichScanActivity.this, ProductDetailsActivity.class);
                    intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, id);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(RichScanActivity.this, "二维码格式不正确\n"+result, Toast.LENGTH_SHORT).show();
                    doRichScan();//开启重建
                }
            } else if(containSku) {
                String sku = result.substring(result.indexOf("sku/") + 4);
                getProductIdBySku(sku);
            } else if (containSku2) {
                String sku = MyUtil.getUrlValueByName(result, "sku");
                getProductIdBySku(sku);
            } else {
                Toast.makeText(RichScanActivity.this, "二维码格式不正确\n"+result, Toast.LENGTH_SHORT).show();
                doRichScan();//开启重建
            }

        }

        @Override
        public void onAnalyzeFailed() {
            analyzeFailed();
        }
    };

    /**
     * 二维码解析错误的处理
     */
    private void analyzeFailed() {
        ToastUtil.showLongToast(this, R.string.rich_scan_error);
        doRichScan();//开启重建
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GlobalConfig.REQUEST_SYSTEM_IMAGE) {
            if (resultCode == RESULT_OK) {
                if (null != data) {
                    Uri uri = data.getData();
                    ContentResolver cr = getContentResolver();
                    String path = ImageUtil.getRealPathFromUri(this, uri);
                    CodeUtils.analyzeBitmap(path, analyzeCallback);
                }
            }

        }
    }

    @Override
    public void onGranted() {
        createFragment();
    }

    @Override
    public void onDenied(List<String> deniedPermissions) {
        ToastUtil.showCustomDurationToast(this, R.string.permission_denied_des, 3000, getString(R.string.permission_camera));
        RichScanActivity.this.finish();
    }

    private void doRichScan() {
        rock = true; //开启重建
        if (rock) {
            createFragment();
            rock = false;
        }
    }

    private void createFragment() {
        captureFragment = new CaptureFragment();
        CodeUtils.setFragmentArgs(captureFragment, R.layout.rich_scan_camera);
        captureFragment.setAnalyzeCallback(analyzeCallback);
        getSupportFragmentManager().beginTransaction().replace(R.id.flContent, captureFragment).commit();
    }

    /**
     * 截取字符串之间
     */
    public String cutStrBetween(String str, String start, String end) {
        if (str != null && str.length() >0) {
            String tempStr;
            tempStr = str.substring(str.indexOf(str+1), str.lastIndexOf(str));
            return tempStr;
        }
        return null;
    }


    private void getProductIdBySku(String sku) {
        OkGo.<String>get(NetWorkPath.GET_PRODUCT_DETAIL+"?"+"sku="+sku)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseData(response);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtil.showShortToast(getParent(), R.string.network_msg);
                        doRichScan();//开启重建
                    }
                });
    }

    /**
     * 解析通过sku搜索商品返回的数据
     * @param response
     */
    private void parseData(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject object = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    JSONObject objSub = object.getJSONObject("data");
                    if (objSub.length() > 0 && objSub != null) {
                        String id =  objSub.getString("id");
                        if (id != null) {
                            Intent intent = new Intent(RichScanActivity.this, ProductDetailsActivity.class);
                            intent.putExtra(IntentCode.EXTRA_KEY_PRODUCT_ID, id);
                            startActivity(intent);
                            finish();
                        }
                    } else {
                        ToastUtil.showShortToast(this, "未找到商品");
                        doRichScan();//开启重建
                    }
                } else {
                    ToastUtil.showShortToast(this, "未找到商品");
                    doRichScan();//开启重建
                }
            } catch (JSONException e) {
                e.printStackTrace();
                ToastUtil.showShortToast(this, "数据解析错误");
                doRichScan();//开启重建
            }
        } else {
            ToastUtil.showShortToast(this, response.body().toString());
            doRichScan();//开启重建
        }
    }
}
